import React, { useState, useEffect, useRef } from 'react'
import { Table, Switch, Button, Modal } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import UserForm from '../../../components/user-manage/UserForm';
import axios from 'axios';

const { confirm } = Modal

export default function UserList() {
  const [userList, setUserList] = useState([]);
  const [open, setOpen] = useState(false)
  const [openUpdate, setopenUpdate] = useState(false)
  const [regionList, setRegionList] = useState([]);//区域列表
  const [roleList, setRoleList] = useState([]);//角色列表
  // const [user, setUser] = useState({});
  const [current, setCurrent] = useState(null);//存储要更新的是哪一个用户
  const [isUpdateDisabled, setisUpdateDisabled] = useState(false);//该属性会传递给子组件UserForm，控制区域下拉列表
  // 请求用户列表
  const { username, roleId, region } = JSON.parse(localStorage.getItem('token'))
  useEffect(() => {
    const roleObject = {
      '1': 'superadmin',
      '2': 'admin',
      '3': 'editor'
    }
    axios.get('/users?_expand=role').then(res => {
      console.log(res.data)
      //说明是全球编辑
      setUserList(roleObject[roleId] === 'superadmin' ? res.data : [...res.data.filter(item => item.username === username), ...res.data.filter(item => item.region === region && roleObject[item.roleId] === 'editor')])
    }
    )
  }, [])

  // 请求区域
  useEffect(() => {
    axios.get('/regions').then(res => {
      setRegionList(res.data)
    })
  }, [])
  // 请求角色列表
  useEffect(() => {
    axios.get('/roles').then(res => {
      console.log(res.data)
      setRoleList(res.data)
    })
  }, [])
  // 给添加表单绑定ref属性
  const addForm = useRef(null);
  // 模态框"添加角色"确定按钮事件
  const addFormOk = () => {
    addForm.current
      .validateFields()  //该方法得到的是表单里的所有数据，返回值是个promise ，该方法是触发表单验证
      .then((values) => {
        setOpen(false);
        // 虽然现在能拿到表单里所有的数据，但格式和请求回来的不一样，缺少id，所以签发请求，就会有id，再去改变状态
        addForm.current.resetFields();//清空表单里的数据
        axios.post('/users', {
          ...values,
          "roleState": true,
          "default": false
        }).then(res => {//res.data是从服务器返回的完整的被添加的用户信息
          setUserList([...userList, { ...res.data, role: roleList.filter(item => item.id === values.roleId)[0] }])
          console.log(res.data)
        })
      })
      .catch((info) => {
        console.log('Validate Failed:', info);
      });
  }
  // 删除事件
  function confirmMethod(row) {
    confirm({
      title: '你确定删除当前项吗？',
      icon: <ExclamationCircleOutlined />,
      onOk() {

        setUserList(userList.filter(item => item.id !== row.id))
        axios.delete(`/users/${row.id}`)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  // 药丸事件--->这个事件会联动登录事件
  const handle = (row) => {
    row.roleState = !row.roleState;
    setUserList([...userList]);
    axios.patch(`/users/${row.id}`, {
      roleState: row.roleState
    })
  }


  // 给更新表单绑定ref属性
  const updateForm = useRef(null)
  // 更新某一个角色
  const updateFormOk = () => {
    updateForm.current
      .validateFields()  //该方法得到的是表单里的所有数据，返回值是个promise ，该方法是触发表单验证
      .then(value => {
        setopenUpdate(false);
        setUserList(userList.map(item => {
          if (item.id === current.id) {
            return {
              ...item, ...value, role: roleList.filter(data => data.id === value.roleId)[0]
            }
          }
          return item
        }))
        axios.patch(`/users/${current.id}`, value)
      })
  }
  // 更改当前角色
  const updateUser = (row) => {
    setopenUpdate(true);
    setTimeout(() => {
      updateForm.current.setFieldsValue(row)
    }, 100)
    setisUpdateDisabled(row.roleId === 1);//如果是roleId====1，说明是超级管理员
    setCurrent(row)
  }
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      filters: [...regionList.map(item => {
        return {
          text: item.label,
          value: item.value
        }
      }),
      {
        text: '全球',
        value: '全球'
      }],
      onFilter: (value, item) => {
        if (value === '') {//如果value是‘’那么选中的就是全球
          return item.region === ''
        } else {
          return item.region === value
        }
      }, //value是当前选中的哪个区域，item是regionList的每一项
      render: (region) => <b>{region === "" ? '全球' : region}</b>
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => role?.roleName
    },
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, row) => <Switch checked={roleState} disabled={row.default} onChange={() => handle(row)}></Switch>
    },
    {
      title: '操作',
      render: (row) => {
        return <div>
          <Button danger shape="circle" icon={<DeleteOutlined />} disabled={row.default} onClick={() => confirmMethod(row)} />
          <Button type="primary" shape="circle" icon={<EditOutlined onClick={() => updateUser(row)} />} disabled={row.default} />
        </div>
      }
    }
  ]
  return (
    <div>
      <Button type="primary" onClick={() => { setOpen(true) }}>添加用户</Button>
      <Table dataSource={userList} columns={columns} rowKey={(row) => row.id} pagination={{ pageSize: 5 }}></Table>
      <Modal
        open={open}
        title="添加用户"
        cancelText="取消"
        onText="确定"
        onCancel={() => { setOpen(false) }}
        onOk={() => addFormOk()}
      >
        <UserForm regionList={regionList} roleList={roleList} ref={addForm}></UserForm>
      </Modal>
      <Modal
        open={openUpdate}
        title="更新用户"
        cancelText="取消"
        onText="更新"
        onCancel={() => {
          setopenUpdate(false);
        }}
        onOk={() => updateFormOk()}
        destroyOnClose  //销毁表单
      >
        <UserForm regionList={regionList} roleList={roleList} ref={updateForm} isUpdateDisabled={isUpdateDisabled} isUpdate={true}></UserForm>
      </Modal>
    </div>
  )
}
